<template>
  <div class="app-container">

    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          
                         
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
                <el-cascader  ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="selectTenant" clearable collapse-tags filterable></el-cascader>
            </el-form-item>

             <el-form-item>
                 <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan" collapse-tags clearable filterable></el-cascader>
            </el-form-item>
    
          <el-form-item>
            <el-input v-model="query.params.storeName" placeholder="店铺名称" />
          </el-form-item>
        
          <el-form-item>
            <el-select v-model="query.params.enable" placeholder="是否生效">
              <el-option
                v-for="item in query.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>

    </div>

    <div class="block">
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="属性组织" width="110">
          <template slot-scope="scope">
            {{ scope.row.organId }}
          </template>
        </el-table-column>
        <el-table-column label="组织路径" width="110">
          <template slot-scope="scope">
            {{ scope.row.organPath }}
          </template>
        </el-table-column>
        <el-table-column label="打印格式尾" width="110">
          <template slot-scope="scope">
            {{ scope.row.printBottom }}
          </template>
        </el-table-column>
        <el-table-column label="打印头" width="110">
          <template slot-scope="scope">
            {{ scope.row.printHead }}
          </template>
        </el-table-column>
        <el-table-column label="店铺图标" width="110">
          <template slot-scope="scope">
            {{ scope.row.storeIcon }}
          </template>
        </el-table-column>
        <el-table-column label="店铺管理员" width="110">
          <template slot-scope="scope">
            {{ scope.row.storeManager }}
          </template>
        </el-table-column>
        <el-table-column label="店铺名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.storeName }}
          </template>
        </el-table-column>
          <el-table-column label="添加者" width="110">
          <template slot-scope="scope">
            {{ scope.row.createBy }}
          </template>
        </el-table-column>
        <el-table-column label="添加时间" width="110">
          <template slot-scope="scope">
            {{ scope.row.createDate }}
          </template>
        </el-table-column>
        <el-table-column label="是否生效" width="110">
          <template slot-scope="scope">
            {{ scope.row.enable }}
          </template>
        </el-table-column>
        <el-table-column label="更新者" width="110">
          <template slot-scope="scope">
            {{ scope.row.updateBy }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="110">
          <template slot-scope="scope">
            {{ scope.row.updateDate }}
          </template>
        </el-table-column>

        <el-table-column  fixed="right"  align="center" prop="created_at" label="操作" width="200">
          <template slot-scope="scope">
            <span class="el-tag el-tag--info el-tag--mini" style="cursor: pointer;" @click="handleEdit(scope.$index, scope.row)">
              {{ scope.row.isSet?'保存':"修改" }}
            </span>
            <span v-if="!scope.row.isSet" class="el-tag el-tag--danger el-tag--mini" style="cursor: pointer;" @click="handleDelete(scope.$index, scope.row)">
              删除
            </span>
            <span v-else class="el-tag  el-tag--mini" style="cursor: pointer;" @click="pwdChange(scope.row,scope.$index,false)">
              取消
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="block">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form">

          <el-form-item  v-if="addForVisible" label="主键">
            <el-input v-model="form.id" placeholder="主键" auto-complete="off" />
          </el-form-item>

          <el-form-item label="店铺名称">
            <el-input v-model="form.storeName" placeholder="店铺名称" auto-complete="off" />
          </el-form-item>
           <el-form-item label="店铺管理员">
            <el-input v-model="form.storeManager" placeholder="店铺管理员" auto-complete="off" />
          </el-form-item>

          <el-form-item label="店铺图标">
            <el-input v-model="form.storeIcon" placeholder="店铺图标" auto-complete="off" />
          </el-form-item>
        

           <el-form-item label="是否生效">
            <el-select v-model="form.enable" placeholder="是否生效" style="width: 100%;" >
              <el-option
                v-for="item in query.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="打印格式尾">
            <el-input v-model="form.printBottom" placeholder="打印格式尾" auto-complete="off" />
          </el-form-item>
          <el-form-item label="打印头">
            <el-input v-model="form.printHead" placeholder="打印头" auto-complete="off" />
          </el-form-item>
       
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>

</template>

<script>
import { getList, doDelete, doEdit } from '@/api/StoreInfo/'
import { getList as getOrganList, querySubordinateOrgan } from '@/api/Organ'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSuperManagerId, getSelectedNodes, getSelectedNodesObject, getSystemErrorCode, getCurrentTimeYYYY_MM_dd_HH_mm_ss } from '@/api/utils'
import localStorageUtil from '@/utils/localStorageUtil'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(status) {
      const typeMap = {
        '1': '超级管理员',
        '2': '管理员',
        '3': '普通用户'
      }
      const typeDesc = typeMap[status]
      return typeDesc
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      addForVisible: false,
      form: {
        createBy: '',
        createDate: '',
        enable: '',
        id: '',
        organId: '',
        organPath: '',
        printBottom: '',
        printHead: '',
        storeIcon: '',
        storeManager: '',
        storeName: '',
        updateBy: '',
        updateDate: ''
      },
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增',
        edit: '编辑'
      },
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath:false
        // disabled:true
      },
      optionData: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          createBy: '', // 添加者
          createDate: '', // 添加时间
          enable: '', // 是否生效
          id: '', // 主键
          organId: '', // 属性组织
          organPath: '', // 组织路径
          printBottom: '', // 打印格式尾
          printHead: '', // 打印头
          storeIcon: '', // 店铺图标
          storeManager: '', // 店铺管理员
          storeName: '', // 店铺名称
          updateBy: '', // 更新者
          updateDate: '' // 更新时间

        },
        timeValue: '',
        options: [{
          value: '1',
          label: '黄金糕'
        }, {
          value: '2',
          label: '双皮奶'
        }, {
          value: '3',
          label: '蚵仔煎'
        }, {
          value: '4',
          label: '龙须面'
        }, {
          value: '5',
          label: '北京烤鸭'
        }],
        value: ''
      }
    }
  },
  created() {
      this.initOrganTree(()=>{
        this.setOrganQueryType()
    })
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      this.createOrganQuery()
      this.currentPage = this.currentPage || 1
      this.pageSize = this.pageSize || 10
      getList(this.query.params, this.currentPage, this.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = data.entities
        this.listLoading = false
      })
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.createBy = ''
      this.form.createDate = ''
      this.form.enable = ''
      this.form.id = ''
      this.form.organId = ''
      this.form.organPath = ''
      this.form.printBottom = ''
      this.form.printHead = ''
      this.form.storeIcon = ''
      this.form.storeManager = ''
      this.form.storeName = ''
      this.form.updateBy = ''
      this.form.updateDate = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      console.log(index)
      console.log(row)

      this.form.createBy = row.createBy
      this.form.createDate = row.createDate
      this.form.enable = row.enable
      this.form.id = row.id
      this.form.organId = row.organId
      this.form.organPath = row.organPath
      this.form.printBottom = row.printBottom
      this.form.printHead = row.printHead
      this.form.storeIcon = row.storeIcon
      this.form.storeManager = row.storeManager
      this.form.storeName = row.storeName
      this.form.updateBy = row.updateBy
      this.form.updateDate = row.updateDate

      this.addForVisible = true

      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData()
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave() {
      debugger

      doEdit(this.form).then(response => {
        debugger
        console.log(response)
        const data = response.data
        if (data.status) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData()
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }
        this.listLoading = false
        this.dialogFormVisible = false
      })
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    initOrganTree(fn) {
      this.listLoading = true
      querySubordinateOrgan({ organId: getOrganId() }).then(response => {
          console.log(response)
          const data = response.data.data
          this.optionData = handleBuildTreeDataStruct(data, 'id', 'parentId')
          this.listLoading = false
          fn()
      })
    },
    setOrganQueryType(){
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes){
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
          this.query.params.organIds = []
          if (nodesInfo.length) {
              nodesInfo.forEach(function(element){
                  that.query.params.organIds.push(element.data.id)
              })
          }
      } else {             
          this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    organQueryModelChange(organQueryModel) {
      if(organQueryModel == 'selected') {
          this.props.multiple=true
      }else if(organQueryModel == 'selfAndSub') {
          this.props.multiple=false
      }
    }
  }
}
</script>
